package com.colin.jipay.pinduoduo_hook;

import android.app.Activity;

import com.colin.jipay.utils.JsonUtils;

import org.json.JSONObject;

import de.robv.android.xposed.XC_MethodHook;
import de.robv.android.xposed.XposedBridge;
import de.robv.android.xposed.XposedHelpers;
import de.robv.android.xposed.callbacks.XC_LoadPackage;

/**
 * @author lemlin
 * @date 2019/7/23
 * <p>
 * 拼多多买家版
 */
public class PDDBuyerHook {

    private XC_LoadPackage.LoadPackageParam lpparam;

    public PDDBuyerHook(XC_LoadPackage.LoadPackageParam lpparam){
        this.lpparam = lpparam;
    }

    /**
     * Hook 拼多多阿里支付信息
     */
    public void hookPddAlipay() {
        //拦截支付信息
        XposedHelpers.findAndHookMethod(XposedHelpers.findClassIfExists("com.xunmeng.pinduoduo.auth.pay.alipay.a", lpparam.classLoader),
                "c", Activity.class, String.class, new XC_MethodHook() {
                    @Override
                    protected void beforeHookedMethod(MethodHookParam param) throws Throwable {
                        super.beforeHookedMethod(param);
                        JSONObject jsonObject = new JSONObject(param.args[1].toString());
                        String orderInfo = jsonObject.optString(("order_info"));
                        XposedBridge.log("入参【Hook 拼多多支付宝支付信息】=》\n" + orderInfo);
                    }
                });
    }


    /**
     * 在结算页面（CheckoutFragment）自动下单支付
     * 1.当进入该页面时拼多多默认请求获取CheckoutResult信息合成到CheckoutEntity实体类中
     * 2.根据CheckoutEntity信息获取OrderResponse信息
     * 3.根据OrderResponse信息获取支付秘钥
     * 4.根据秘钥拉起支付宝支付
     * 信息如下：
     * 入参【CheckoutResult结算返回信息】：{"addressVO":{"address":"金港路金山桔园和园28栋1梯502","addressId":"9196040244","canGoodsSoldHere":true,"city":"福州市","district":"仓山区","labels":[],"mobile":"18396125445","name":"林荔敏","province":"福建省","provinceId":"4"},"confirmCode":0,"couponVO":{"mallPromotion":{"batchId":"1159130342","category":"店铺优惠","couponStatus":3,"discount":500,"displayName":"领券满49减5元","displayType":8,"eventDiscount":0,"isReachMinAmount":false,"isSuperpositionCoupon":false,"minAmount":4900,"notUse":false},"platformPromotion":{"category":"平台优惠","couponStatus":0,"discount":0,"displayType":0,"isPlatformCouponForbidden":false,"isReachMinAmount":false,"isSuperpositionCoupon":false,"minAmount":0,"notUse":false}},"destinationUrl":"group7.html","goodsVo":{"allowedRegion":["2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17","18","19","20","21","22","23","24","25","26","27","30","31","32"],"categoryId":"7799","categoryId1":"7639","categoryId2":"7664","categoryId3":"7799","categoryId4":"0","costProvinceCodes":"5,9,19,20,21,28,29","costTemplateId":"2381628","deliveryStatus":0,"eventType":0,"goodsId":"101908032","goodsName":"汽车内饰清洗剂顶棚内部室内绒布织物真皮座椅去污多功能强力清洁","goodsNumber":1,"goodsType":1,"hasPromotion":false,"huabeiStatus":0,"invoiceStatus":0,"isCustoms":false,"labels":[{"content":"拼单成功6小时内，待发货状态下，提交退款申请将立即退款","css":{"fontColor":"#339B29","fontSize":12},"title":"极速退款","type":7}],"limitNum":53823,"mallId":"646261","realNameAuth":false,"unitPrice":2090},"groupVO":{"buyLimit":999999,"customerNum":1,"endTime":2082729600,"groupId":"203186240","orderLimit":999999,"startTime":1451577600},"mallVO":{"canCompensate":false,"id":"646261","logo":"http://t16img.yangkeduo.com/pdd_ims/bda366545242811633a12278c6b7ec72.JPG","name":"Rubson车品旗舰店"},"merchantPromotionPrice":0,"morganStatus":"0","orderPrice":2090,"orderServicePath":"order","payPrice":2090,"payVO":{"payChannelList":[{"appId":"4","display":true,"enable":true,"payContentVO":{"content":"微信支付","cssVO":{"fontColor":"#151516","fontSize":15}},"paySubContentVO":{"content":" (推荐)","cssVO":{"fontColor":"#58595B","fontSize":14}},"rank":1,"sign":false},{"appId":"35","display":true,"enable":true,"payContentVO":{"content":"支付宝","cssVO":{"fontColor":"#151516","fontSize":15}},"paySubContentVO":{"content":"","cssVO":{"fontColor":"#58595B","fontSize":14}},"rank":2,"sign":false},{"appId":"-1","display":true,"enable":true,"payContentVO":{"content":"找微信好友支付","cssVO":{"fontColor":"#151516","fontSize":15}},"paySubContentVO":{"content":"","cssVO":{"fontColor":"#58595B","fontSize":14}},"rank":4,"sign":false},{"appId":"12","display":false,"enable":true,"payContentVO":{"content":"QQ钱包","cssVO":{"fontColor":"#151516","fontSize":15}},"paySubContentVO":{"content":"","cssVO":{"fontColor":"#58595B","fontSize":14}},"rank":5,"sign":false}]},"platformPromotionPrice":0,"serverTime":1562672418,"shippingPrice":0,"skuVO":{"groupPrice":1990,"limitQuantity":999999,"normalPrice":2090,"quantity":53823,"skuId":"127644151288","spec":[{"specKey":"组合","specValue":"内饰顶棚清洗+内饰镀膜洗护组合一"}],"specifications":["组合: 内饰顶棚清洗+内饰镀膜洗护组合一"],"thumbUrl":"http://t00img.yangkeduo.com/goods/images/2018-12-18/447d6437550c4c67d986c78291d978db.png","wareId":"0","weight":1200},"tipList":[]}
     * 获取【CheckoutEntity成员变量信息】：{"a":{"a":{"props":"{\"sku_id\":\"127644151288\",\"group_id\":\"203186240\",\"goods_id\":\"101908032\",\"goods_number\":\"1\",\"ts\":\"1562672417296\",\"page_from\":\"35\",\"url\":\"order_checkout.html?goods_id\u003d101908032\u0026page_from\u003d35\u0026sku_id\u003d127644151288\u0026goods_number\u003d1\u0026group_id\u003d203186240\u0026ts\u003d1562672417296\"}","type":"pdd_order_confirm","url":"order_checkout.html?goods_id\u003d101908032\u0026page_from\u003d35\u0026sku_id\u003d127644151288\u0026goods_number\u003d1\u0026group_id\u003d203186240\u0026ts\u003d1562672417296"},"c":{"page_from":"35","goods_number":"1","group_id":"203186240","goods_id":"101908032","sku_id":"127644151288","ts":"1562672417296"},"e":"order_checkout.html?goods_id\u003d101908032\u0026page_from\u003d35\u0026sku_id\u003d127644151288\u0026goods_number\u003d1\u0026group_id\u003d203186240\u0026ts\u003d1562672417296","f":"101908032","g":"127644151288","h":"203186240","j":1,"l":"35","m":0,"n":0,"o":0},"b":"101908032","c":"127644151288","d":"203186240","f":1,"h":{"addressVO":{"address":"金港路金山桔园和园28栋1梯502","addressId":"9196040244","canGoodsSoldHere":true,"city":"福州市","district":"仓山区","labels":[],"mobile":"18396125445","name":"林荔敏","province":"福建省","provinceId":"4"},"confirmCode":0,"couponVO":{"mallPromotion":{"batchId":"1159130342","category":"店铺优惠","couponStatus":3,"discount":500,"displayName":"领券满49减5元","displayType":8,"eventDiscount":0,"isReachMinAmount":false,"isSuperpositionCoupon":false,"minAmount":4900,"notUse":false},"platformPromotion":{"category":"平台优惠","couponStatus":0,"discount":0,"displayType":0,"isPlatformCouponForbidden":false,"isReachMinAmount":false,"isSuperpositionCoupon":false,"minAmount":0,"notUse":false}},"destinationUrl":"group7.html","goodsVo":{"allowedRegion":["2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17","18","19","20","21","22","23","24","25","26","27","30","31","32"],"categoryId":"7799","categoryId1":"7639","categoryId2":"7664","categoryId3":"7799","categoryId4":"0","costProvinceCodes":"5,9,19,20,21,28,29","costTemplateId":"2381628","deliveryStatus":0,"eventType":0,"goodsId":"101908032","goodsName":"汽车内饰清洗剂顶棚内部室内绒布织物真皮座椅去污多功能强力清洁","goodsNumber":1,"goodsType":1,"hasPromotion":false,"huabeiStatus":0,"invoiceStatus":0,"isCustoms":false,"labels":[{"content":"拼单成功6小时内，待发货状态下，提交退款申请将立即退款","css":{"fontColor":"#339B29","fontSize":12},"title":"极速退款","type":7}],"limitNum":53823,"mallId":"646261","realNameAuth":false,"unitPrice":2090},"groupVO":{"buyLimit":999999,"customerNum":1,"endTime":2082729600,"groupId":"203186240","orderLimit":999999,"startTime":1451577600},"mallVO":{"canCompensate":false,"id":"646261","logo":"http://t16img.yangkeduo.com/pdd_ims/bda366545242811633a12278c6b7ec72.JPG","name":"Rubson车品旗舰店"},"merchantPromotionPrice":0,"morganStatus":"0","orderPrice":2090,"orderServicePath":"order","payPrice":2090,"payVO":{"payChannelList":[{"appId":"4","display":true,"enable":true,"payContentVO":{"content":"微信支付","cssVO":{"fontColor":"#151516","fontSize":15}},"paySubContentVO":{"content":" (推荐)","cssVO":{"fontColor":"#58595B","fontSize":14}},"rank":1,"sign":false},{"appId":"35","display":true,"enable":true,"payContentVO":{"content":"支付宝","cssVO":{"fontColor":"#151516","fontSize":15}},"paySubContentVO":{"content":"","cssVO":{"fontColor":"#58595B","fontSize":14}},"rank":2,"sign":false},{"appId":"-1","display":true,"enable":true,"payContentVO":{"content":"找微信好友支付","cssVO":{"fontColor":"#151516","fontSize":15}},"paySubContentVO":{"content":"","cssVO":{"fontColor":"#58595B","fontSize":14}},"rank":4,"sign":false},{"appId":"12","display":false,"enable":true,"payContentVO":{"content":"QQ钱包","cssVO":{"fontColor":"#151516","fontSize":15}},"paySubContentVO":{"content":"","cssVO":{"fontColor":"#58595B","fon
     * 入参【OrderResponse订单返回信息】：{"group_order_id":"815328941896391625","is_paid":false,"order_amount":2090,"order_sn":"190709-328941896391625","server_time":1562672420}
     * 入参【支付宝支付秘钥信息】：{"server_time":1562672420,"status":10000,"order_info":"service=mobile.securitypay.pay&partner=2088911201740274&sign_type=RSA&sign=TiHL9FBv0d8RSq0cn99agHh5MyU%2BKz3Lvkg0XXMLKpVwNRUCHmCsPpH5DCxG0nexNvZ1GKC37paGhTgGPYjbOWcLbqMzp%2Bve72RLegZ6%2BFBjWJiuFVBqYr3YEGlSLhXAQTQ97eF7PH4uh1Y6Vvl4Rs3lzbuAXdh6YP1vb57dyGM%3D&notify_url=http:\/\/payv3.yangkeduo.com\/notify\/6&out_trade_no=XP0019070919201655524476005145&subject=订单编号190709-328941896391625&payment_type=1&seller_id=pddzhifubao@yiran.com&total_fee=20.9&body=订单编号190709-328941896391625&goods_type=1&_input_charset=utf-8"}
     */
    public void hookAutoOrders() {

        //HOOK CheckoutResult结算返回信息（在拼多多中CheckoutResult包含了地址、物品、交易方式等信息），并拉起支付
        XposedHelpers.findAndHookMethod(XposedHelpers.findClassIfExists("com.xunmeng.pinduoduo.checkout.f", lpparam.classLoader),
                "a", XposedHelpers.findClassIfExists("com.xunmeng.pinduoduo.checkout.data.response.CheckoutResult", lpparam.classLoader), new XC_MethodHook() {
                    @Override
                    protected void afterHookedMethod(MethodHookParam param) throws Throwable {
                        super.afterHookedMethod(param);
                        XposedBridge.log("入参【CheckoutResult结算返回信息】：" + JsonUtils.objectToString(param.args[0]));

                        Object thisObject = param.thisObject;
                        Object aObject = XposedHelpers.getObjectField(thisObject, "d");
                        XposedBridge.log("获取【CheckoutEntity成员变量信息】：" + JsonUtils.objectToString(aObject));
                        //拉起支付n方法
                        XposedHelpers.callMethod(thisObject, "n");
                    }
                });

        //HOOK OrderResponse返回信息（在拼多多中此方法会根据OrderResponse获取支付秘钥）
        XposedHelpers.findAndHookMethod(XposedHelpers.findClassIfExists("com.xunmeng.pinduoduo.checkout.f", lpparam.classLoader),
                "a", XposedHelpers.findClassIfExists("com.xunmeng.pinduoduo.entity.order.OrderResponse", lpparam.classLoader), new XC_MethodHook() {
                    @Override
                    protected void beforeHookedMethod(MethodHookParam param) throws Throwable {
                        super.beforeHookedMethod(param);
                        XposedBridge.log("入参【OrderResponse订单返回信息】：" + JsonUtils.objectToString(param.args[0]));
                    }
                });

        //HOOK 在拼多多中此方法获取秘钥信息，获取成功后将会自动拉起拼多多中的支付宝支付，如有需要也可在此做从外部拉起支付
        XposedHelpers.findAndHookMethod(XposedHelpers.findClassIfExists("com.xunmeng.pinduoduo.common.pay.a", lpparam.classLoader),
                "a", int.class, JSONObject.class, new XC_MethodHook() {
                    @Override
                    protected void beforeHookedMethod(MethodHookParam param) throws Throwable {
                        super.beforeHookedMethod(param);
                        XposedBridge.log("入参【支付宝支付秘钥信息】：" + param.args[1]);
                    }
                });
    }

}
